package sk.tramtatiri.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.FriendshipDao;
import sk.tramtatiri.data.dataobjects.Friendship;
import sk.tramtatiri.data.dataobjects.User;
import sk.tramtatiri.data.dataobjects.UserFood;

public class FriendshipDaoJPAImp extends AbstractDaoJPAImpl<Friendship> implements FriendshipDao {

	public FriendshipDaoJPAImp() {
		super(Friendship.class);
		// TODO Auto-generated constructor stub
	}

	public List<Friendship> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	public Friendship findName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Transactional
	public List<User> findAllFriendsOfUser(final long user_id) {
		return getJpaTemplate().execute(new JpaCallback<List<User>>() {
			public List<User> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u, Friendship f where u.id = f.friend_id and f.user_id = :userId order by u.nickname", User.class);
				query.setParameter("userId", user_id);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public List<User> findAllFriedsSharingStats(final long user_id) {
		return getJpaTemplate().execute(new JpaCallback<List<User>>() {
			public List<User> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u, Friendship f where u.id = f.user_id and f.friend_id = :userId and f.sharedStats = 1 order by u.nickname", User.class);
				query.setParameter("userId", user_id);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public void delete(Friendship o) {
		Friendship f = getJpaTemplate().find(Friendship.class, o.getId());
		getJpaTemplate().remove(f);
	}

}
